/*!
 * @Author: CPS
 * @email: 373704015@qq.com
 * @Date: 2020-08-24 00:18:12
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-31 13:08:00
 * @Projectname Electron-fileWatcher
 * @file_path "D:\CPS\MyProject\Electron-fileWatcher\src\renderer\api\router\index.js"
 * @Filename "index.js"
 */
'use strict'
/* 路由: /watcher/xxxxx
/* 监听一个目录 */
import watcher from './watcherRouter.js'

/* 路由: /YYS/xxxx
/* 返回所有后台相关的数据*/
import YYS from './YYSRouter.js'

/* 路由: /config/xxxxx
/* 返回相关配置 */
import config from './configRouter.js'

/* 路由: /folder/xxxx
/* 读取本地文件夹信息,返回对象结构 */
import folder from './folderRouter.js'

/* 路由: /exec/xxxx
/* 打开对应的[文件/文件夹] */
import cmd from './cmdRouter.js'

const Router = {
  config,
  folder,
  YYS,
  cmd,
  watcher
}

for (let each in Router) {
  // 添加一个临时容器
  let fun = Router[each]
  Router[each] = function(action, data) {
    if (fun.hasOwnProperty(action)) {
      return fun[action](data)
    }
  }
}

/* 根路由 只支持2做到2级 */
const router = {
  'config': function(action) {
    if (config.hasOwnProperty(action)) {
      return config[action]()
    }
  },

  'folder': function(action, data) {
    if (folder.hasOwnProperty(action)) {
      return folder[action](data)
    }
  },

  'YYS': function() {
    return YYS
  },

  'open': function(target) {
    return cmd.open(target)
  }
}

/**
 * 伪路由解释 .... 去掉前后的 "/" 转换为小写
 *
 * @param      {string}  action  The action
 * @return     {array}  [1级请求,2级请求...]
 */
function parse(action) {
  return action.replace(/^\/|\/$/g, '').split('/')
}

// 模拟get...
function get(action, callback) {
  let tar = parse(action)
  let req = { stat: 404 }

  let [first, second, ...left] = [...tar]
  if (callback) {
    /*如果给予的对象是回调函数,则进行回调*/
    callback(null, router[first](second))
  } else {
    /*如果给予的是数据,则执行*/
    router[first](second)
  }
}

// 模拟post....
function post(action, data, callback) {
  let tar = parse(action)
  let req = { stat: 404 }
  let res = ''
  let router = Router

  let [first, second, ...left] = [...tar]
  if (!router.hasOwnProperty(first)) {
    return
  }

  switch (tar.length) {
    case 1: //1级路由
      res = router[first](data)
      break;

    case 2: //2级路由
      res = router[first](second, data)

      if (callback) {
        /*如果给予的对象是回调函数,则进行回调*/
        return callback(res)
      }
      break;
    default:
      // statements_def
      break;
  }

  return res
}

export default (() => {
  log('++尝试载入++ Router')

  // 确保对象全局唯一性
  if (!global.Router) {
    log('--创建Router')
    global.Router = {
      get,
      post
    }
  }

  return global.Router
})()
